package cn.school.prevention.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.school.common.utils.SysUserUtils;
import cn.school.prevention.dao.FeedBackDao;
import cn.school.prevention.dao.ScopeDao;
import cn.school.prevention.entity.FeedBack;
import cn.school.prevention.entity.Info;
import cn.school.prevention.entity.Scope;
import cn.school.prevention.service.ScopeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ScopeServiceImpl extends ServiceImpl<ScopeDao, Scope> implements ScopeService {

    @Autowired
    private ScopeDao scopeDao;

    @Autowired
    private FeedBackDao feedBackDao;

    @Override
    public IPage<Scope> scopePageList(Scope scope) {
        LambdaQueryWrapper<Scope> wrapper=new LambdaQueryWrapper<>();
        Info info=new Info();
        Long id = info.getId();
        wrapper.eq(Scope::getPiId,id);
        wrapper.orderByDesc(Scope::getId);
        IPage<Scope> page = page(new Page<>(scope.getPageNum(), scope.getPageSize()), wrapper);
        return page;
    }

    @Override
    public int insert(Scope scope) {
        String userName = SysUserUtils.getSysUser().getUsername();
        scope.setCreateBy(userName);
        scope.setCreateTime(new Date());
        return scopeDao.insert(scope);
    }

    @Override
    public IPage<Scope> page(Scope scope) {
        int count = scopeDao.count(scope);
        int startNum = (scope.getPageNum() - 1) * scope.getPageSize();
        scope.setPageNum(startNum);
        List<Scope> commentList = scopeDao.list(scope);
        IPage<Scope> page = new Page<>();
        page.setTotal(count);
        page.setRecords(commentList);
        return page;

    }

    @Override
    public int update(Scope scope) {
        String userName = SysUserUtils.getSysUser().getUsername();
        scope.setModifyBy(userName);
        scope.setModifyTime(new Date());
        if("1".equals(scope.getIsFeedback())){
            scope.setFeedbackTime(DateUtil.formatDateTime(new Date()));
        }
        List<FeedBack> feedBacks = scope.getFeedBacks();
        for(FeedBack ss:feedBacks){
            ss.setModifyBy(userName);
            ss.setModifyTime(new Date());
            ss.setFeedbackTime(DateUtil.formatDateTime(new Date()));
            feedBackDao.updateById(ss);
        }
        return scopeDao.updateById(scope);
    }


}
